"""
语音配置实体模型
"""

from sqlalchemy import (
    Column, String, Text, Integer, Float, Boolean, 
    JSON, Enum as SQLEnum, DateTime, ForeignKey
)
from sqlalchemy.orm import relationship, declarative_base
from datetime import datetime
from enum import Enum
import uuid

from ..core.database import Base


class VoiceGender(Enum):
    """语音性别"""
    MALE = "male"
    FEMALE = "female"
    NEUTRAL = "neutral"


class VoiceEngine(Enum):
    """TTS引擎"""
    PYTTSX3 = "pyttsx3"
    AZURE = "azure"
    GOOGLE = "google"
    AMAZON = "amazon"
    CUSTOM = "custom"


class VoiceProfile(Base):
    """语音配置模型"""
    __tablename__ = "voice_profiles"
    
    id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
    name = Column(String(100), nullable=False, index=True)
    description = Column(Text, nullable=True)
    
    # 语音基本信息
    language = Column(String(10), nullable=False, default="zh-CN", index=True)
    gender = Column(SQLEnum(VoiceGender), default=VoiceGender.NEUTRAL)
    engine = Column(SQLEnum(VoiceEngine), default=VoiceEngine.PYTTSX3)
    voice_id = Column(String(100), nullable=True)  # 引擎特定的语音ID
    
    # 语音参数
    rate = Column(Integer, default=200)           # 语速 50-500
    volume = Column(Float, default=0.9)           # 音量 0.0-1.0
    pitch = Column(Integer, default=50)           # 音调 0-100
    
    # 高级设置
    emphasis = Column(Float, default=1.0)          # 重音强度 0.5-2.0
    pause_duration = Column(Float, default=0.5)    # 停顿时长 0.0-5.0秒
    breathing = Column(Boolean, default=False)     # 是否添加呼吸声
    
    # 音频输出设置
    sample_rate = Column(Integer, default=22050)   # 采样率
    channels = Column(Integer, default=1)         # 声道数
    format = Column(String(10), default="wav")     # 音频格式
    
    # 自定义设置
    custom_settings = Column(JSON, nullable=True)  # 引擎特定设置
    
    # 状态信息
    is_active = Column(Boolean, default=True)
    is_system = Column(Boolean, default=False)     # 是否系统预设
    is_public = Column(Boolean, default=True)      # 是否公开
    
    # 使用统计
    usage_count = Column(Integer, default=0)       # 使用次数
    rating = Column(Float, default=0.0)            # 平均评分
    rating_count = Column(Integer, default=0)      # 评分人数
    
    # 用户关联
    user_id = Column(String, nullable=True, index=True)  # 创建者ID，系统预设为NULL
    
    # 时间戳
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    last_used_at = Column(DateTime, nullable=True)
    
    # 关系
    presets = relationship("VoicePreset", back_populates="voice_profile", cascade="all, delete-orphan")
    reviews = relationship("VoiceProfileReview", back_populates="voice_profile", cascade="all, delete-orphan")
    
    def __repr__(self):
        return f"<VoiceProfile(id='{self.id}', name='{self.name}', engine='{self.engine.value}')>"
    
    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "name": self.name,
            "description": self.description,
            "language": self.language,
            "gender": self.gender.value,
            "engine": self.engine.value,
            "voice_id": self.voice_id,
            "rate": self.rate,
            "volume": self.volume,
            "pitch": self.pitch,
            "emphasis": self.emphasis,
            "pause_duration": self.pause_duration,
            "breathing": self.breathing,
            "sample_rate": self.sample_rate,
            "channels": self.channels,
            "format": self.format,
            "custom_settings": self.custom_settings,
            "is_active": self.is_active,
            "is_system": self.is_system,
            "is_public": self.is_public,
            "usage_count": self.usage_count,
            "rating": self.rating,
            "rating_count": self.rating_count,
            "user_id": self.user_id,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None,
            "last_used_at": self.last_used_at.isoformat() if self.last_used_at else None
        }


class VoicePreset(Base):
    """语音预设模型"""
    __tablename__ = "voice_presets"
    
    id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
    voice_profile_id = Column(String, ForeignKey("voice_profiles.id"), nullable=False, index=True)
    
    # 预设信息
    name = Column(String(50), nullable=False)
    description = Column(Text, nullable=True)
    
    # 预设参数 (覆盖voice_profile的设置)
    rate = Column(Integer, nullable=True)
    volume = Column(Float, nullable=True)
    pitch = Column(Integer, nullable=True)
    emphasis = Column(Float, nullable=True)
    pause_duration = Column(Float, nullable=True)
    breathing = Column(Boolean, nullable=True)
    
    # 使用场景
    usage_scenario = Column(String(50), nullable=True)  # 如：narration, dialogue, reading等
    emotion_style = Column(String(50), nullable=True)   # 如：happy, sad, neutral等
    
    # 预设状态
    is_active = Column(Boolean, default=True)
    is_system = Column(Boolean, default=False)     # 是否系统预设
    
    # 使用统计
    usage_count = Column(Integer, default=0)
    
    # 用户关联
    user_id = Column(String, nullable=True, index=True)
    
    # 时间戳
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    
    # 关系
    voice_profile = relationship("VoiceProfile", back_populates="presets")
    
    def __repr__(self):
        return f"<VoicePreset(id='{self.id}', name='{self.name}', voice_profile_id='{self.voice_profile_id}')>"
    
    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "voice_profile_id": self.voice_profile_id,
            "name": self.name,
            "description": self.description,
            "rate": self.rate,
            "volume": self.volume,
            "pitch": self.pitch,
            "emphasis": self.emphasis,
            "pause_duration": self.pause_duration,
            "breathing": self.breathing,
            "usage_scenario": self.usage_scenario,
            "emotion_style": self.emotion_style,
            "is_active": self.is_active,
            "is_system": self.is_system,
            "usage_count": self.usage_count,
            "user_id": self.user_id,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None
        }


class VoiceProfileReview(Base):
    """语音配置评论模型"""
    __tablename__ = "voice_profile_reviews"
    
    id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
    voice_profile_id = Column(String, ForeignKey("voice_profiles.id"), nullable=False, index=True)
    user_id = Column(String, nullable=False, index=True)
    
    # 评论信息
    rating = Column(Integer, nullable=False)         # 评分 1-5
    title = Column(String(200), nullable=True)       # 评论标题
    content = Column(Text, nullable=True)            # 评论内容
    
    # 使用体验
    clarity = Column(Integer, default=0)              # 清晰度 1-5
    naturalness = Column(Integer, default=0)          # 自然度 1-5
    stability = Column(Integer, default=0)            # 稳定性 1-5
    pronunciation = Column(Integer, default=0)         # 发音准确性 1-5
    
    # 统计信息
    helpful_count = Column(Integer, default=0)       # 有用数
    is_public = Column(Boolean, default=True)        # 是否公开
    
    # 时间戳
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    
    # 关系
    voice_profile = relationship("VoiceProfile", back_populates="reviews")
    
    def __repr__(self):
        return f"<VoiceProfileReview(id='{self.id}', rating={self.rating}, voice_profile_id='{self.voice_profile_id}')>"
    
    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "voice_profile_id": self.voice_profile_id,
            "user_id": self.user_id,
            "rating": self.rating,
            "title": self.title,
            "content": self.content,
            "clarity": self.clarity,
            "naturalness": self.naturalness,
            "stability": self.stability,
            "pronunciation": self.pronunciation,
            "helpful_count": self.helpful_count,
            "is_public": self.is_public,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None
        }


class VoiceUsageLog(Base):
    """语音使用日志模型"""
    __tablename__ = "voice_usage_logs"
    
    id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
    voice_profile_id = Column(String, ForeignKey("voice_profiles.id"), nullable=False, index=True)
    user_id = Column(String, nullable=False, index=True)
    
    # 使用信息
    session_id = Column(String, nullable=True)       # 会话ID
    text_length = Column(Integer, default=0)         # 文本长度
    audio_duration = Column(Float, default=0.0)      # 音频时长
    generation_time = Column(Float, default=0.0)    # 生成时间(秒)
    
    # 请求参数
    used_preset = Column(String, nullable=True)     # 使用的预设
    custom_parameters = Column(JSON, nullable=True) # 自定义参数
    
    # 结果信息
    success = Column(Boolean, default=True)         # 是否成功
    error_message = Column(Text, nullable=True)      # 错误信息
    
    # 客户端信息
    client_ip = Column(String(45), nullable=True)    # 客户端IP
    user_agent = Column(Text, nullable=True)         # 用户代理
    
    # 时间戳
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    
    def __repr__(self):
        return f"<VoiceUsageLog(id='{self.id}', voice_profile_id='{self.voice_profile_id}', success={self.success})>"
    
    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "voice_profile_id": self.voice_profile_id,
            "user_id": self.user_id,
            "session_id": self.session_id,
            "text_length": self.text_length,
            "audio_duration": self.audio_duration,
            "generation_time": self.generation_time,
            "used_preset": self.used_preset,
            "custom_parameters": self.custom_parameters,
            "success": self.success,
            "error_message": self.error_message,
            "client_ip": self.client_ip,
            "user_agent": self.user_agent,
            "created_at": self.created_at.isoformat() if self.created_at else None
        }


class VoiceFavorite(Base):
    """语音收藏模型"""
    __tablename__ = "voice_favorites"
    
    id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
    voice_profile_id = Column(String, ForeignKey("voice_profiles.id"), nullable=False, index=True)
    user_id = Column(String, nullable=False, index=True)
    
    # 收藏信息
    category = Column(String(50), nullable=True)    # 收藏分类
    notes = Column(Text, nullable=True)             # 备注
    
    # 时间戳
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    
    def __repr__(self):
        return f"<VoiceFavorite(id='{self.id}', voice_profile_id='{self.voice_profile_id}', user_id='{self.user_id}')>"
    
    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "voice_profile_id": self.voice_profile_id,
            "user_id": self.user_id,
            "category": self.category,
            "notes": self.notes,
            "created_at": self.created_at.isoformat() if self.created_at else None
        }
